package cn.usian.comon.iterceptor;

import cn.usian.jyzx.model.entity.user.UserInfo;
import cn.usian.jyzx.model.vo.common.Result;
import cn.usian.jyzx.model.vo.common.ResultCodeEnum;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws IOException {

//
        String url = request.getRequestURI().toString();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/api/**/auth/**", url);

        if (match){          //url.contains("auth")
            System.out.println("需要拦截");
            String token = request.getHeader("token");
            String userInfoJson = redisTemplate.opsForValue().get(token);
            UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
            if (userInfo !=null){
                AutoThreadLocal.threadLocal.set(userInfo);
                return true;
            }
            Result build = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
//            将响应的对象转换成json 格式
            String str = JSON.toJSONString(build);
            response.getWriter().write(str);
            return false;
        }else {
            return  true;
        }
    }
}
